package com.tuananh.radnom.service.discovery.impl;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.tuananh.radnom.model.NetInterface;
import com.tuananh.radnom.model.NetNode;
import com.tuananh.radnom.model.discovery.DiscoverNetInt;
import com.tuananh.radnom.model.netservice.NetService;
import com.tuananh.radnom.model.protocol.netbios.ActiveNetBios.NetbiosInfo;
import com.tuananh.radnom.model.protocol.service.AbstractDiscover;
import com.tuananh.radnom.model.protocol.service.ActiveDiscover;
import com.tuananh.radnom.service.config.impl.DiscoverService;
import com.tuananh.radnom.service.config.impl.NetIntService;
import com.tuananh.radnom.service.config.impl.NetNodeService;
import com.tuananh.radnom.service.discovery.AbstractDiscoverd;

public class ActiveDiscoverd extends AbstractDiscoverd {
	public void run() {
		// TODO Auto-generated method stub
		// discovers.get(0).addObserver(this);
		if (getDiscoverService().isActiveDiscover()) {
			ArrayList<ActiveDiscover> discovers = getDiscoverService()
					.getAllActiveDiscover();
			ArrayList<String> results = new ArrayList<String>();
			ExecutorService pool = Executors.newCachedThreadPool();
			ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(
					20);
			setStop(false);
			for (ActiveDiscover discover : discovers) {
				if (discover.isEnable()) {
					discover.addObserver(this);
					if (discover.getInterval() > 0) {
						ScheduledFuture<?> scheduleAtFixedRate = executor
								.scheduleAtFixedRate(discover, 0,
										discover.getInterval(),
										TimeUnit.SECONDS);
					} else {
						Future<?> future = pool.submit(discover);
						try {
							future.get(discover.getTimeout(), TimeUnit.SECONDS);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (ExecutionException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (TimeoutException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}

			try {
				Thread.sleep(40000);
				setStop(true);
				Thread.sleep(10000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			setStop(false);
			while (!isStop()) {
				try {
					Thread.sleep(50);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
			pool.shutdownNow();
			executor.shutdownNow();
		}
	}
}
